# -*- coding: utf-8 -*-
import time
import requests
import base64


class Field(object):
    def __init__(self, string=None, field_name=None, help=None):
        self.string = string
        self.field_name = field_name
        self.help = help
        pass

    def value_get(self, val):
        return val


class Char(Field):
    def value_get(self, val):
        return val or ''
    pass


class Datetime(Field):
    pass


class Selection(Field):
    def __init__(self, selection=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.selection = selection

    def value_get(self, val):
        ops = dict(self.selection)
        return ops[val]


class Float(Field):
    def value_get(self, val):
        return float(val or '0.0')


class Integer(Field):
    def value_get(self, val):
        return int(val)


class One2many(Field):
    def __init__(self, comodel=None, * args, **kwargs):
        super().__init__(*args, **kwargs)
        self.comodel = comodel

    def value_get(self, val):
        return [self.comodel.value_get(record) for record in val]


class TimeInteger(Field):
    def value_get(self, val):
        val2 = time.localtime(val/1000)
        val2 = time.strftime('%Y-%m-%d %H:%M:%S', val2)
        return val2


class DateYYYYMMDD(Field):
    def value_get(self, val):
        if len(val) != 8:
            return '1900-01-01'

        val2 = val[0:4] + '-' + val[4:6] + '-' + val[6:]
        return val2


class PdfURL(Field):
    def value_get(self, val, order_name):
        if not val:
            return None

        response = requests.get(val)
        datas = base64.b64encode(response.content)
        val2 = {
            'name': order_name + '.pdf',
            'datas': datas,
            'mimetype': 'application/pdf'
        }
        return val2
